import routingService from "@/api/services/mes/routingService";
import workOrderService, {
  type PageListReq,
} from "@/api/services/mes/workOrderService";
import workshopService from "@/api/services/mes/workshopService";
import CustomTable from "@/components/grid/CustomTable";
import TableDictTag from "@/components/grid/TableDictTag";
import useDictionary from "@/hooks/system/useDictionary";
import { t } from "@/locales/i18n";
import SingleMaterialSelector from "@/pages/components/selector/SingleMaterialSelect";
import { DownOutlined, ExportOutlined } from "@ant-design/icons";
import {
  Button,
  Card,
  Col,
  DatePicker,
  Drawer,
  Dropdown,
  Form,
  Input,
  InputNumber,
  Modal,
  Progress,
  Row,
  Select,
  Space,
  Spin,
  Tabs,
} from "antd";
import type { MenuProps } from "antd";
import { useWatch } from "antd/es/form/Form";
import type { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import type { Action } from "#/entity";
import type { MesRouting } from "../routing/entity";
import type { MesWorkshop } from "../workshop/entity";
import MesWorkOrderBomItemPage, {
  type MesWorkOrderBomItemHandles,
} from "./bomItem";
import MesWorkOrderBomSubstitutePage, {
  type MesWorkOrderBomSubstituteHandles,
} from "./bomSubstitute";
import type { MesWorkOrder, MesWorkOrderBomItem } from "./entity";
import KitCheckModal from "./kitCheck";
import MesWorkOrderProcessPage, {
  type MesWorkOrderProcessHandles,
} from "./process";

const { TextArea } = Input;

export default function MesWorkOrderPage() {
  const itemRef = useRef<MesWorkOrderBomItemHandles>(null);
  const [bomItemList, setBomItemList] = useState<MesWorkOrderBomItem[]>([]);

  const substituteRef = useRef<MesWorkOrderBomSubstituteHandles>(null);
  const processRef = useRef<MesWorkOrderProcessHandles>(null);

  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    workOrderCode: undefined,
    workOrderType: undefined,
    productId: undefined,
    orderSource: undefined,
    lineId: undefined,
    parentId: undefined,
    status: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<MesWorkOrder[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingData, setEditingData] = useState<MesWorkOrder | null>(null);
  const [isView, setIsView] = useState(true);

  const [routingOptions, setRoutingOptions] = useState<MesRouting[]>([]);
  const [selectMaterialVisiable, setSelectMaterialVisiable] = useState(false);
  const [workshopOptions, setWorkshopOptions] = useState<MesWorkshop[]>([]);
  const [lineOptions, setLineOptions] = useState<MesWorkshop[]>([]);

  const [kitCheckOpen, setKitCheckOpen] = useState(false);
  const [kitCheckWorkOrderId, setKitCheckWorkOrderId] =
    useState<React.Key>(null);

  //工单拆分
  const [splitModalVisible, setSplitModalVisible] = useState(false);
  const [splitRecord, setSplitRecord] = useState<MesWorkOrder | null>(null);
  const [splitQty, setSplitQty] = useState<number | undefined>(undefined);

  // 下达弹窗相关状态
  const [transmitModalVisible, setTransmitModalVisible] = useState(false);
  const [transmitRecord, setTransmitRecord] = useState<MesWorkOrder | null>(
    null
  );
  const [transmitForm] = Form.useForm();

  const [form] = Form.useForm();
  // 监听整个表单数据
  const formValues = useWatch([], form); // 空数组表示监听所有字段

  const workOrderStatusOptions = useDictionary("work_order_status");

  const allActions: Action[] = [
    {
      label: t("common.view"),
      type: "view",
      clickHandler: (record) => handleView(record),
    },
    {
      label: t("common.edit"),
      type: "edit",
      clickHandler: (record) => handleEdit(record),
    },
    {
      label: "下达",
      type: "transmit",
      clickHandler: (record) => handleTransmit(record),
    },
    {
      label: "拆分",
      type: "split",
      clickHandler: (record) => handleSplit(record),
    },
    {
      label: "齐套分析",
      type: "completeset",
      clickHandler: (record) => handleKitCheck(record),
    },
    {
      label: "标签打印",
      type: "print",
      clickHandler: (record) => console.log("标签打印", record),
    },
    {
      label: "挂起",
      type: "stop",
      clickHandler: (record) => console.log("完成", record),
    },
  ];

  const actionMap: Record<string, string[]> = {
    PREPARE: ["view", "edit", "transmit", "completeset", "print", "split"],
    RELEASED: ["view", "stop", "print"],
    IN_PROGRESS: ["view", "stop", "print"],
    PAUSED: ["view"],
    CLOSED: ["view"],
    CANCELED: ["view"],
    FINISHED: ["view"],
    APPROVING: ["view", "print"],
    APPROVED: ["view", "print"],
  };

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 405;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  useEffect(() => {
    getWorkshopOptions();
  }, []);

  const workOrderTypeOptions = useDictionary("work_order_type");

  const columns: ColumnsType<MesWorkOrder> = [
    {
      title: "工单编码",
      width: 150,
      key: "workOrderCode",
      dataIndex: "workOrderCode",
    },
    {
      title: "工单类型",
      width: 120,
      key: "workOrderType",
      dataIndex: "workOrderType",
      render: (_, record) => (
        <TableDictTag
          dictCode="work_order_type"
          value={record.workOrderType ?? ""}
        />
      ),
    },
    {
      title: "产品编码",
      width: 150,
      key: "productCode",
      dataIndex: "productCode",
    },
    {
      title: "产品名称",
      width: 200,
      key: "productName",
      dataIndex: "productName",
    },
    {
      title: "生产数量",
      width: 120,
      key: "planQty",
      dataIndex: "planQty",
    },
    {
      title: "单据状态",
      width: 120,
      key: "status",
      dataIndex: "status",
      render: (_, record) => (
        <TableDictTag
          dictCode="work_order_status"
          value={record.status ?? ""}
        />
      ),
    },
    {
      title: "工艺路线",
      width: 120,
      key: "routingName",
      dataIndex: "routingName",
    },
    {
      title: "车间",
      width: 120,
      key: "workshopName",
      dataIndex: "workshopName",
    },
    {
      title: "产线",
      width: 120,
      key: "lineName",
      dataIndex: "lineName",
    },
    {
      title: "计划开工时间",
      width: 120,
      key: "startTime",
      dataIndex: "startTime",
    },
    {
      title: "计划完工时间",
      width: 120,
      key: "endTime",
      dataIndex: "endTime",
    },
    {
      title: "实际完工数量",
      width: 120,
      key: "actualQty",
      dataIndex: "actualQty",
    },
    {
      title: "已排产数量",
      width: 120,
      key: "quantityScheduled",
      dataIndex: "quantityScheduled",
    },
    {
      title: "实际开工时间",
      width: 120,
      key: "actualStartTime",
      dataIndex: "actualStartTime",
    },
    {
      title: "实际完工时间",
      width: 120,
      key: "actualEndTime",
      dataIndex: "actualEndTime",
    },
    {
      title: "进度",
      width: 120,
      key: "progress",
      dataIndex: "progress",
      render: (value: number) => <Progress percent={value} size="small" />,
    },
    {
      title: "报废数量",
      width: 120,
      key: "scrapQty",
      dataIndex: "scrapQty",
      render: (value: number) => (
        <span style={{ color: "red", fontWeight: "bold" }}>{value}</span>
      ),
    },
    {
      title: "返工数量",
      width: 120,
      key: "reworkQty",
      dataIndex: "reworkQty",
      render: (value: number) => (
        <span style={{ color: "red", fontWeight: "bold" }}>{value}</span>
      ),
    },
    {
      title: "是否完工",
      width: 120,
      key: "completionFlag",
      dataIndex: "completionFlag",
      render: (_, record) => (
        <TableDictTag
          dictCode="system_true_false"
          value={record.completionFlag ?? ""}
        />
      ),
    },
    {
      title: "延迟原因说明",
      width: 120,
      key: "delayReason",
      dataIndex: "delayReason",
    },
    {
      title: "优先级",
      width: 120,
      key: "priority",
      dataIndex: "priority",
    },
    {
      title: "备注",
      width: 120,
      key: "remark",
      dataIndex: "remark",
    },
    {
      title: "操作",
      fixed: "right",
      key: "operation",
      align: "center",
      width: 180,
      render: (_: any, record: any) => {
        const availableTypes = actionMap[record.status] || [];
        const availableButtons = allActions.filter((action) =>
          availableTypes.includes(action.type)
        );

        const visibleButtons = availableButtons.slice(0, 2);
        const dropdownButtons = availableButtons.slice(2);

        const dropdownMenu: MenuProps["items"] = dropdownButtons.map((btn) => ({
          key: btn.type,
          label: (
            <span onClick={() => btn.clickHandler(record)}>{btn.label}</span>
          ),
        }));

        return (
          <Space>
            {visibleButtons.map((btn) => (
              <Button
                key={btn.type}
                type="link"
                onClick={() => btn.clickHandler(record)}
              >
                {btn.label}
              </Button>
            ))}
            {dropdownButtons.length > 0 && (
              <Dropdown menu={{ items: dropdownMenu }}>
                <Button icon={<DownOutlined />} iconPosition="end" type="link">
                  更多
                </Button>
              </Dropdown>
            )}
          </Space>
        );
      },
    },
  ];

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    workOrderService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // 获取产品工艺路线
  const getProductRouting = async (productId: React.Key) => {
    await routingService
      .getProductRouting(productId)
      .then((res) => {
        setRoutingOptions(res);
      })
      .catch((error) => {
        console.error("获取产品工艺路线失败：", error);
        toast.error("获取产品工艺路线失败");
      });
  };

  // 获取车间下拉列表
  const getWorkshopOptions = () => {
    workshopService
      .getWorkshopSelectList()
      .then((res) => {
        setWorkshopOptions(res);
      })
      .catch((error) => {
        console.error("获取车间列表失败：", error);
        toast.error("获取车间列表失败");
      });
  };

  // 获取车间下拉列表
  const getLineOptions = async (workshopId: number) => {
    await workshopService
      .getLineSelectList(workshopId)
      .then((res) => {
        setLineOptions(res);
      })
      .catch((error) => {
        console.error("获取产线列表失败：", error);
        toast.error("获取产线列表失败");
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  //触发编辑按钮
  const handleEdit = (mesWorkOrder: MesWorkOrder) => {
    setEditingData(mesWorkOrder);

    const productId = mesWorkOrder.productId;
    if (productId) {
      getProductRouting(productId);
    }
    const workshopId = mesWorkOrder.workshopId;
    if (workshopId) {
      getLineOptions(workshopId);
    }

    form.setFieldsValue(mesWorkOrder);
    setDrawerVisible(true);
    setIsView(false);
  };

  //触发视图按钮
  const handleView = (mesWorkOrder: MesWorkOrder) => {
    setEditingData(mesWorkOrder);

    const productId = mesWorkOrder.productId;
    if (productId) {
      getProductRouting(productId);
    }
    const workshopId = mesWorkOrder.workshopId;
    if (workshopId) {
      getLineOptions(workshopId);
    }

    form.setFieldsValue(mesWorkOrder);
    setIsView(true);
    setDrawerVisible(true);
  };

  //提交表单数据
  const handleSubmit = async (values: MesWorkOrder) => {
    try {
      setSubmitLoading(true);

      //生产工单BOM组成
      const deleteItemIds = itemRef.current?.getDeleteIds();
      const addItems = itemRef.current?.getAddList();
      const updateItems = itemRef.current?.getUpdateList();

      //工单替代料
      const deleteSubstituteIds = substituteRef.current?.getDeleteIds();
      const addSubstitutes = substituteRef.current?.getAddList();
      const updateSubstitutes = substituteRef.current?.getUpdateList();

      //工单工艺路线
      const deleteProcessIds = processRef.current?.getDeleteIds();
      const addProcessList = processRef.current?.getAddList();
      const updateProcessList = processRef.current?.getUpdateList();

      const data = {
        ...values,
        id: editingData?.id,
        deleteItemIds: deleteItemIds,
        addItems: addItems,
        updateItems: updateItems,
        deleteSubstituteIds: deleteSubstituteIds,
        addSubstitutes: addSubstitutes,
        updateSubstitutes: updateSubstitutes,
        deleteProcessIds: deleteProcessIds,
        addProcessList: addProcessList,
        updateProcessList: updateProcessList,
      };
      if (editingData) {
        await workOrderService.update(data);
        toast.success("更新生产工单成功");
      } else {
        await workOrderService.add(data);
        toast.success("创建生产工单成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingData(null);
    form.resetFields();
  };

  const handleAdd = () => {
    setEditingData(null);
    form.resetFields();
    form.setFieldValue("workOrderType", "normal");
    setDrawerVisible(true);
    setIsView(false);
  };

  const handleDelete = async () => {
    try {
      setLoading(true);
      await workOrderService.remove(selectedRowKeys);
      toast.success("删除生产工单成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`删除失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const openSelectMaterial = (id: React.Key) => {
    setSelectMaterialVisiable(true);
  };

  const handleSelectMaterial = (material: any) => {
    setSelectMaterialVisiable(false);
    if (material) {
      const { id, materialCode, materialName, spec } = material;
      form.setFieldsValue({
        productId: id,
        productCode: materialCode,
        productName: materialName,
        productSpec: spec,
      });

      //获取工艺路线
      getProductRouting(id);
    }
  };

  // 拆分按钮处理
  const handleSplit = (record: MesWorkOrder) => {
    setSplitRecord(record);
    setSplitQty(undefined);
    setSplitModalVisible(true);
  };

  // 拆分确认
  const handleSplitConfirm = async () => {
    if (!splitQty || splitQty <= 0) {
      toast.error("请输入有效的拆分数量");
      return;
    }

    //计划数量
    const planQty = splitRecord?.planQty;
    if (planQty && splitQty > planQty) {
      toast.error("拆分数量不能大于计划生产数");
      return;
    }

    try {
      setLoading(true);
      await workOrderService.split(splitRecord?.id, splitQty);
      toast.success("工单拆分成功");
      setSplitModalVisible(false);
      setSplitRecord(null);
      setSplitQty(undefined);
      fetchPageList();
    } catch (error) {
      toast.error(`拆分失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  //齐套分析
  const handleKitCheck = (record: MesWorkOrder) => {
    if (record.id) {
      setKitCheckOpen(true);
      setKitCheckWorkOrderId(record?.id);
    }
  };

  // 工单下达
  const handleTransmit = (record: MesWorkOrder) => {
    setTransmitRecord(record);
    transmitForm.setFieldsValue(record);
    setTransmitModalVisible(true);
  };

  // 下达确认
  const handleTransmitConfirm = async () => {
    try {
      const values = await transmitForm.validateFields();
      setLoading(true);
      await workOrderService.transmit({
        ...transmitRecord,
        ...values,
      });
      toast.success("工单下达成功");
      setTransmitModalVisible(false);
      setTransmitRecord(null);
      fetchPageList();
    } catch (error: any) {
      toast.error(`下达失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Card className="mb-4">
        <Form
          layout="inline"
          onFinish={(values) => {
            setQueryParams((prev) => ({
              ...prev,
              ...values,
              page: 1,
            }));
          }}
        >
          <Form.Item name="workOrderCode" label="工单编码">
            <Input placeholder="请输入工单编码" allowClear />
          </Form.Item>
          <Form.Item name="workOrderType" label="工单类型">
            <Select
              options={workOrderTypeOptions}
              placeholder="请输入工单类型"
              allowClear
              style={{ width: 170 }}
            />
          </Form.Item>
          <Form.Item name="productCode" label="产品编码">
            <Input placeholder="产品编码" allowClear />
          </Form.Item>
          <Form.Item name="status" label="单据状态">
            <Select
              options={workOrderStatusOptions}
              placeholder="请输入单据状态"
              allowClear
              style={{ width: 170 }}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <CustomTable
          loading={loading}
          columnsConfig={columns}
          dataSource={list}
          total={total}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
          current={queryParams.page}
          pageSize={queryParams.pageSize}
          onRefresh={fetchPageList}
          onPageChange={handlePageChange}
          selectable
          toolbarButtons={
            <>
              <Button type="primary" onClick={handleAdd}>
                新增
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleDelete}
              >
                删除
              </Button>
            </>
          }
          scroll={{ y: tableScrollY }}
        />
      </Card>
      <Drawer
        title={editingData ? "编辑生产工单" : "新增生产工单"}
        width={1000}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            {!isView && (
              <Button
                type="primary"
                loading={submitLoading}
                onClick={() => form.submit()}
              >
                确定
              </Button>
            )}
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleSubmit}
          disabled={isView}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="workOrderCode" label="工单编码">
                <Input placeholder="请输入工单编码" disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="workOrderType"
                label="工单类型"
                rules={[
                  {
                    required: true,
                    message: "请填写工单类型",
                  },
                ]}
              >
                <Select options={workOrderTypeOptions} allowClear />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="productId" label="产品ID" hidden>
                <Input />
              </Form.Item>
              <Form.Item
                label="产品编码"
                name="productCode"
                rules={[{ required: true, message: "请选择产品编码" }]}
              >
                <Input.Search
                  placeholder="请选择生产产品"
                  allowClear
                  enterButton={<ExportOutlined />}
                  onSearch={openSelectMaterial}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="productName" label="产品名称">
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="planQty"
                label="生产数量"
                rules={[
                  {
                    required: true,
                    message: "请填写生产数量",
                  },
                ]}
              >
                <InputNumber
                  placeholder="请输入生产数量"
                  style={{ width: "100%" }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="routingId" label="工艺路线">
                <Select
                  options={routingOptions.map((item) => ({
                    label: item.name,
                    value: item.id,
                  }))}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="workshopId" label="车间">
                <Select
                  options={workshopOptions.map((item) => ({
                    label: item.name,
                    value: item.id,
                  }))}
                  onChange={(value) => getLineOptions(value)}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="lineId" label="产线">
                <Select
                  options={lineOptions.map((item) => ({
                    label: item.name,
                    value: item.id,
                  }))}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="startTime"
                label="计划开工时间"
                rules={[
                  {
                    required: true,
                    message: "请填写计划开工时间",
                  },
                ]}
                getValueFromEvent={(value) => {
                  return value ? value.format("YYYY-MM-DD") : null;
                }}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  format="YYYY-MM-DD"
                  onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="endTime"
                label="计划完工时间"
                rules={[
                  {
                    required: true,
                    message: "请填写计划完工时间",
                  },
                ]}
                getValueFromEvent={(value) => {
                  return value ? value.format("YYYY-MM-DD") : null;
                }}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  format="YYYY-MM-DD"
                  onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                name="remark"
                label="备注"
                labelCol={{ span: 3 }}
                wrapperCol={{ span: 21 }}
              >
                <TextArea />
              </Form.Item>
            </Col>
          </Row>

          <Tabs
            defaultActiveKey="1"
            items={[
              {
                key: "1  ",
                label: "BOM组成",
                children: (
                  <MesWorkOrderBomItemPage
                    ref={itemRef}
                    parentId={editingData?.id}
                    formValues={formValues}
                    onListChange={(list) => setBomItemList(list)}
                  />
                ),
              },
              {
                key: "2  ",
                label: "替代料",
                children: (
                  <MesWorkOrderBomSubstitutePage
                    ref={substituteRef}
                    parentId={editingData?.id}
                    bomItemList={bomItemList}
                  />
                ),
              },
              {
                key: "3  ",
                label: "工艺路线",
                children: (
                  <MesWorkOrderProcessPage
                    ref={processRef}
                    parentId={editingData?.id}
                    formValues={formValues}
                  />
                ),
              },
            ]}
          />
        </Form>
      </Drawer>

      {/* 物料选择器 */}
      <SingleMaterialSelector
        open={selectMaterialVisiable}
        onCancel={() => setSelectMaterialVisiable(false)}
        onOk={(item) => handleSelectMaterial(item)}
      />

      {/* 工单拆分 */}
      <Modal
        title="工单拆分"
        open={splitModalVisible}
        onCancel={() => setSplitModalVisible(false)}
        onOk={handleSplitConfirm}
        okText="确定"
        cancelText="取消"
      >
        <div>
          <div>工单编码：{splitRecord?.workOrderCode}</div>
          <InputNumber
            style={{ width: "100%", marginTop: 16 }}
            min={1}
            placeholder="请输入拆分数量"
            value={splitQty}
            onChange={setSplitQty}
          />
        </div>
      </Modal>

      <KitCheckModal
        open={kitCheckOpen}
        onCancel={() => setKitCheckOpen(false)}
        workOrderId={kitCheckWorkOrderId}
      />

      {/* 下达弹窗 */}
      <Modal
        title="工单下达"
        width={1000}
        open={transmitModalVisible}
        onCancel={() => setTransmitModalVisible(false)}
        onOk={handleTransmitConfirm}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={transmitForm}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          initialValues={transmitRecord || {}}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="工单编码" name="workOrderCode">
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="工单类型" name="workOrderType">
                <Select options={workOrderTypeOptions} disabled />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="产品编码" name="productCode">
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="产品名称" name="productName">
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="生产数量" name="planQty">
                <InputNumber disabled style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="工艺路线" name="routingName">
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="车间" name="workshopName">
                <Select
                  options={workshopOptions.map((item) => ({
                    label: item.name,
                    value: item.id,
                  }))}
                  onChange={(value) => getLineOptions(value)}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="产线" name="lineName">
                <Select
                  options={lineOptions.map((item) => ({
                    label: item.name,
                    value: item.id,
                  }))}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="startTime"
                label="计划开工时间"
                rules={[
                  {
                    required: true,
                    message: "请填写计划开工时间",
                  },
                ]}
                getValueFromEvent={(value) => {
                  return value ? value.format("YYYY-MM-DD") : null;
                }}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  format="YYYY-MM-DD"
                  onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="endTime"
                label="计划完工时间"
                rules={[
                  {
                    required: true,
                    message: "请填写计划完工时间",
                  },
                ]}
                getValueFromEvent={(value) => {
                  return value ? value.format("YYYY-MM-DD") : null;
                }}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  format="YYYY-MM-DD"
                  onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </Spin>
  );
}
